package cn.rengy.tpa.wxmp.jsapi;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JS SDK 管理类
 * <p>参考<a href="http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html">开发文档</a></p>
 */
public class JsApiManager {

    private static Logger logger = LoggerFactory.getLogger(JsApiManager.class);

    /**
     * 给需要调用JS SDK的URL签名
     *
     * @param url
     * @return
     */
    public static JsApiParam signature(String url,String jsapiTicket,String appid) {
        StringBuilder signatureSource = new StringBuilder();
        String nonceStr = RandomStringUtils.randomAlphanumeric(32);
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        //String jsapiTicket = "";//TokenProxy.jsApiTicket();
        signatureSource.append("jsapi_ticket=").append(jsapiTicket);
        signatureSource.append("&noncestr=").append(nonceStr);
        signatureSource.append("&timestamp=").append(timestamp);
        signatureSource.append("&url=").append(url);
        //logger.debug("sign source :{} ",signatureSource);
        String signature = DigestUtils.sha1Hex(signatureSource.toString());
        //logger.debug("sign : {}" , signature);
        return new JsApiParam(url, jsapiTicket, nonceStr, timestamp, signature,appid);
    }

}
